//
//  LKEmoticonTools.swift
//  LKWeibo
//
//  Created by like on 16/8/19.
//  Copyright © 2016年 like. All rights reserved.
//

import UIKit

// 最多显示的列数 和 行数 和最多显示表情个数
let LKEmoticonsMaxCol = 7
let LKEmoticonsMaxRow = 3
let LKEmoticonsMaxCount = LKEmoticonsMaxCol*LKEmoticonsMaxRow - 1

class LKEmoticonTools:NSObject{
    //设置单例
    static let sharedTools: LKEmoticonTools = LKEmoticonTools()
    
    lazy var emoticonsBundle: NSBundle = {
        //路径
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
        //创建bundle
        let bund = NSBundle(path: path!)
        return bund!
    }()
    
    //
    // 默认表情一维数组
    lazy var defaultEmoticons: [LKEmoticonModel] = {
        return self.getEmoticonsWithPath("default")
    }()
    
    // emoji表情一维数组
    lazy var emojiEmoticons: [LKEmoticonModel] = {
        return self.getEmoticonsWithPath("emoji")
    }()
    
    // 浪小花表情一维数组
    lazy var lxhEmoticons: [LKEmoticonModel] = {
        return self.getEmoticonsWithPath("lxh")
    }()
    
    //通过二维 转三维
    lazy var allEmoticons:[[[LKEmoticonModel]]] = {
        return [
            self.getEmotionsGroupsWithEmoticons(self.defaultEmoticons),
            self.getEmotionsGroupsWithEmoticons(self.emojiEmoticons),
            self.getEmotionsGroupsWithEmoticons(self.lxhEmoticons)
        ]
    }()
    
    //通过一维数字 转 二维数字
    func getEmotionsGroupsWithEmoticons(emoticons: [LKEmoticonModel]) -> [[LKEmoticonModel]]{
        // 创建一个可变的二维临时数组
        var tempArray: [[LKEmoticonModel]] = [[LKEmoticonModel]]()
        
        //获取多少页
        let pageNum = (emoticons.count + LKEmoticonsMaxCount - 1)/LKEmoticonsMaxCount
        //遍历
        // 遍历页数
        for i in 0..<pageNum {
            let location = i*LKEmoticonsMaxCount
            var length = LKEmoticonsMaxCount
            // 由于默认表情为108哥  遍历到最后一组 [100,20] 而我们只有 到[100,8]
            if location + length > emoticons.count {
                length = emoticons.count - location
            }
            // 范围
            let range = NSRange(location: location, length: length)
            // 数组截取
            let array = (emoticons as NSArray).subarrayWithRange(range) as![LKEmoticonModel]
            // 添加一维数组
            tempArray.append(array)
        }
        return tempArray
    }
    
    // 读取plist文件 得到一维数组
    func getEmoticonsWithPath(path: String) -> [LKEmoticonModel]{
        let file = emoticonsBundle.pathForResource("\(path)/info.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: file)!

        // 遍历数组 字典转模型
        var tempArray: [LKEmoticonModel] = [LKEmoticonModel]()
        for dic in array{
            let model = LKEmoticonModel(dic: dic as! [String : AnyObject])
            // 设置路径
            model.path = "\(path)/"
            tempArray.append(model)
        }
        return tempArray
    }
    
    
    
    
    
    
    
    
}
